# !usr/python3


import xlrd
import sys
import codecs
import os
import json

def Export2Json(inputFilePath, outputFilePath, fileName):
    book = GetExcelData(inputFilePath);
    if bool is None:
        return

    worksheets = book.sheet_names()
    for sheet in worksheets:
        print('%s,%s' % (worksheets.index(sheet), sheet))
    sheet = book.sheet_by_name(worksheets[0])
    row_0 = sheet.row(0)
    row_1 = sheet.row(1)
    nrows = sheet.nrows
    ncols = sheet.ncols

    GenerateCfg(fileName, sheet)
    GenerateCfgData(fileName);

    result = {}                         # 定义json对象
    result["title"] = fileName          # 表单标题
    result["rows"] = nrows - 5          # 行号
    result["default"] = ""              # 缺省
    result["data"] = []                 # 每一行作为数组的一项
    # 遍历所有行，将excel转化为json对象
    for i in range(nrows):
        if 0 == i  or 1 == i or 3 == i or 4 == i:
            continue
        tmp = {}
        # 遍历当前行所有列、
        for j in range(ncols):
            title_type = str(row_1[j]).split("'")[1]
            if title_type:
                title_de = str(row_0[j])
                title_cn = title_de.split("'")[1]
                # 获取单元格的值
                if "_Array" in title_cn:
                    tmp[title_cn[0:-6]] = FormatArray(title_type,sheet.row_values(i)[j])
                else:
                    tmp[title_cn] = FormatValue(title_type, sheet.row_values(i)[j])

        if 2 == i :
            result["default"] = tmp;
        else:
            result["data"].append(tmp)
    json_data = json.dumps(result, indent=4, sort_keys=False)
    SaveJsonFile(outputFilePath, fileName, json_data)


# 格式化数据
def FormatValue( data_type, value ):
    if "int" == data_type:
        return int(value);
    elif "float" == data_type:
        return float( value );
    elif "string" == data_type:
        return str(value);

# 格式化数组数据
def FormatArray( date_type, value ):
    result = [];
    itemSplits = str(value).split(",")

    for item in itemSplits:
        result.append(FormatValue(date_type,item))

    return result;

def GetFileData( file_path ):
    file = codecs.open(file_path,"r", "utf-8" )
    text = file.read();
    file.close();
    return text

def GetExcelData(inputFilePath):
    try:
        data = xlrd.open_workbook(inputFilePath)
        return data
    except Exception:
        print("excel 读取失败 " + inputFilePath);

def SaveJsonFile( file_path,file_name,data ):
    output = codecs.open(file_path + "/" + file_name + ".json", 'w', "utf-8")
    output.write(data)
    output.close()

def SaveCsFile( file_path,file_name,data ):
    output = codecs.open(file_path + "/" + file_name + ".cs", 'w', "utf-8")
    output.write(data)
    output.close()


def GenerateCfg( fileName, sheet ):
    cfg_templates = GetFileData( "./ConfigTemplates/CfgTemplates.cs" );
    cfg_name = fileName;
    cfg_content = "";
    row_1 = sheet.row(1)
    row_0 = sheet.row(0)
    ncols = sheet.ncols
    for j in range(ncols):
        if 0 == j :
            continue
        title_type = str(row_1[j]).split("'")[1]
        if title_type:
            title_de = str(row_0[j])
            title_cn = title_de.split("'")[1]
            # 获取单元格的值
            if "_Array" in title_cn:
                temp = "        public List<" + str(row_1[j]).split("'")[1] + "> " + title_cn[0:-6] + ";"
            else:
                temp = "        public " + str(row_1[j]).split("'")[1] +" "+ title_cn + ";"
            cfg_content += temp + "\n";

    # 替换保存
    cfg_templates = cfg_templates.replace("CFG_NAME",cfg_name)
    cfg_templates = cfg_templates.replace("CFG_CONTENT", cfg_content)
    #print(cfg_templates)
    SaveCsFile("../Game/Assets/Scripts/Config/Cfg/", cfg_name, cfg_templates);
    return
def GenerateCfgData( fileName ):
    cfg_templates = GetFileData("./ConfigTemplates/CfgDataTemplates.cs");

    cfg_name = fileName;
    cfg_name_data = fileName + "Data";

    cfg_templates = cfg_templates.replace("CFG_NAME_DATA", cfg_name_data)
    cfg_templates = cfg_templates.replace("CFG_NAME", cfg_name)

    #print(cfg_templates)
    SaveCsFile("../Game/Assets/Scripts/Config/Data/", cfg_name_data, cfg_templates);
    return

def GenerateCfgVar( fileNames ):
    cfg_templates = GetFileData("./ConfigTemplates/CfgVarTemplates.cs");
    content_names = "";
    for  name in fileNames:

        content_names += '            "' + name +  '",' + "\n"

    cfg_templates = cfg_templates.replace("CONTENT_NAMES", content_names)
    #print(cfg_templates)
    SaveCsFile("../Game/Assets/Scripts/Config/Var/", "CfgVar", cfg_templates);
    return

if __name__ == "__main__":
    print("__main__");

    path = "./Cfg/";
    exportPath = "../Game/Assets/StreamingAssets/Cfg/";
    files = os.listdir(path)  # 得到文件夹下的所有文件名称
    fileNameDatas = [];
    for file in files:
        if not os.path.isdir(file):  # 判断是否是文件夹，不是文件夹才打开
           cfgName = os.path.splitext(file)[0]
           Export2Json( path + file, exportPath,cfgName );
           fileNameDatas += [cfgName+"Data"];
           
    GenerateCfgVar( fileNameDatas );
    print( fileNameDatas );
    print( "成功导出" );
    input('input:');
